package longrise.phone.com.bjjt_jyb.compensate;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.android.util.IntenetUtil;

import longrise.phone.com.bjjt_jyb.Activity.MainActivity;
import longrise.phone.com.bjjt_jyb.Application.BaseApplication;
import longrise.phone.com.bjjt_jyb.Constant.URLConstant;
import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.Utils.PrefUtils;
import longrise.phone.com.bjjt_jyb.Utils.StringUtils;
import longrise.phone.com.bjjt_jyb.Utils.UiUtil;
import longrise.phone.com.bjjt_jyb.Utils.UiUtils;
import longrise.phone.com.bjjt_jyb.bindinginformation.PersonalInfoView;
import longrise.phone.com.bjjt_jyb.myaccident.AccidentMainView;


public class HomePageView extends LFView implements View.OnClickListener, ILSMsgListener, ILFMsgListener, BDLocationListener {
    private Context context = null;
    private View view = null;
    private LinearLayout ll_homepage_entercompensate;
    private Dialog processDialog;
    private LinearLayout ll_homepage_personinfo;//个人信息
    private LinearLayout ll_homepage_myaccident;//我的事故
    private TextView tv_home_text_3;
    private BaseApplication mApplication;
    private boolean isExit = false;
    private LinearLayout hn_btn_back;
    // 地图定位服务
    private LocationClient mLocationClient = null;
    private Dialog dialog;
    private boolean gpsover = false;
    private ImageView iv_guangbo;
    private TextView tv_guangbo;
    private LinearLayout ll_guangbo;
    private LocationManager locationManager;

    public HomePageView(Context c) {
        super(c);
        this.context = c;
        this.mApplication = (BaseApplication) c.getApplicationContext();
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        initBaidu();
        queryIfbindingInfo();
        /*String remarks = PrefUtils.getString(context, "remarks", "");
        if(!TextUtils.isEmpty(remarks)){
            UiUtils.showRemarksDialog(context,remarks);
            PrefUtils.setString(context,"remarks", "");
        }*/
        int versionCode = UiUtil.getVersionCode();
        //版本更新内容
        int isFirst = PrefUtils.getInt(context, "isFirstnew", 0);
        if (versionCode > isFirst) {
            UiUtils.showRemarksDialog(context, "1、新增修改事故时间功能\n" +
                    "2、修改的事故时间必须在当前时间之前");
            PrefUtils.setInt(context, "isFirstnew", versionCode);
        }
    }


    private void initBaidu() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系，bd09ll为百度的坐标系
        option.setScanSpan(3000);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        // 开始定位
        mLocationClient = new LocationClient(context, option);
        mLocationClient.registerLocationListener(HomePageView.this);
        // 判断是否有网络连接
        if (IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_NONE) {
            Toast.makeText(context, "没有网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        if (null != mLocationClient && !mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        dialog = UiUtil.showProcessDialog(context, "获取位置中...");
    }


    private void initView() {
        view = View.inflate(context, R.layout.view_homepage, null);
        ll_homepage_entercompensate = (LinearLayout) view.findViewById(R.id.ll_homepage_entercompensate);
        ll_homepage_personinfo = (LinearLayout) view.findViewById(R.id.ll_homepage_bindinfo);
        ll_homepage_myaccident = (LinearLayout) view.findViewById(R.id.ll_homepage_myaccident);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        ll_guangbo = (LinearLayout) view.findViewById(R.id.ll_guangbo);
        tv_home_text_3 = (TextView) view.findViewById(R.id.tv_home_text_3);
        iv_guangbo = (ImageView) view.findViewById(R.id.iv_guangbo);
        tv_guangbo = (TextView) view.findViewById(R.id.tv_guangbo);
        TextView tv_home_text1 = (TextView) view.findViewById(R.id.tv_home_text1);
        tv_home_text1.setText(mApplication.getKckpName());
    }

    /**
     * 注册事件
     */
    private void regEvent(boolean b) {
        if (null != ll_homepage_entercompensate) {
            ll_homepage_entercompensate.setOnClickListener(b ? this : null);
        }
        if (null != ll_homepage_personinfo) {
            ll_homepage_personinfo.setOnClickListener(b ? this : null);
        }
        if (null != ll_homepage_myaccident) {
            ll_homepage_myaccident.setOnClickListener(b ? this : null);
        }
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
        }
        if (b) {
            this.addILFMsgListener(this);
        } else {
            this.removeILFMsgListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        switch (v.getId()) {
            case R.id.ll_homepage_entercompensate:
                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    //跳转到提示打开gps界面
                    OpenGpsView opengpsview = new OpenGpsView(context);
                    FrameworkManager.getInstance().showNewForm(context, opengpsview);
                } else {
                    if (gpsover) {
                        //跳转到历史记录界面
                        AccidentMainView accidentView = new AccidentMainView(context);
                        showForm(accidentView);
                    } else {
                        mLocationClient.start();
                        dialog.show();
                    }
                }
                break;
            case R.id.ll_homepage_bindinfo://快处快赔
                queryTime();
                break;
            case R.id.ll_homepage_myaccident://查看我的信息
                enterMyRecommend();
                break;
            case R.id.hn_btn_back://退出界面
                logout();
                break;
            default:
                break;
        }
    }

    /**
     * 进入我的推荐页面
     */
    private void enterMyRecommend() {
        processDialog = UiUtil.showProcessDialog(getContext(), "正在查询...");
        EntityBean bean = new EntityBean();
        bean.set("userflag", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        bean.set("pagenum", "1");
        bean.set("pagesize", "20");
        LoadDataManagerCar.getInstance(context).callService(null, mApplication.getServerUrl(), URLConstant.JJAPPGETMYRECOMMEND, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (result != null) {
                    if (null != processDialog) {
                        if (processDialog.isShowing()) {//消失不会显示进度
                            processDialog.dismiss();
                        }
                    }
                    EntityBean bean = (EntityBean) result;
                    String restate = bean.getString("restate");
                    String redes = bean.getString("redes");
                    EntityBean entityBean = bean.getBean("data");
                    EntityBean[] datas = null;
                    if (null != entityBean) {
                        datas = entityBean.getBeans("carlist");
                    }
                    int number = Integer.valueOf(bean.getString("number"));
                    if ("1".equals(restate)) {
                        PersonalInfoView infoView = new PersonalInfoView(context, null, datas, number);
                        showForm(infoView);
                    } else {
                        UiUtil.showToast(context, redes);
                    }
                }
            }

            @Override
            public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {//消失不会显示进度
                        processDialog.dismiss();
                    }
                }
                UiUtil.showToast(context, "连接超时，请检查网络后重试。");
            }

            @Override
            public void onFinished(String key, String service) {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {//消失不会显示进度
                        processDialog.dismiss();
                    }
                }
            }
        });
    }


    /**
     * 联网查询处理过的数据有多少起，显示到界面上
     */
    private void queryIfbindingInfo() {
        BaseApplication application = (BaseApplication) context
                .getApplicationContext();
        EntityBean userInfo = application.getLoginInfo().getBean("userinfo");
        String url = application.getServerUrl();
        EntityBean bean = new EntityBean();
        bean.set("userid", userInfo.get("id"));//用户id
        bean.set("username", application.getKckpName());//用户名
        bean.set("token", application.getToken());
        bean.set("policeno", "");
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        LoadDataManagerCar.getInstance(context).callService(null, url,
                URLConstant.KCKPJJSEARCHALLCASE, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        checkBind(bean, false);
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(getContext(), "网络服务故障，请稍后重试");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    private void checkBind(EntityBean bean, boolean isToast) {
        String num = bean.getString("data");
        EntityBean play = bean.getBean("play");
        EntityBean[] notices = play.getBeans("notice");
        StringBuilder sBu = new StringBuilder();
        for (int k=0;k<notices.length;k++) {
            String remark = notices[k].getString("remark");
            if(!StringUtils.isEmpty(remark)){
                sBu.append(remark);
                sBu.append("                               " +
                        "                               " +
                        "                               " +
                        "                               ");
            }
        }
        if (!StringUtils.isEmpty(sBu.toString())) {
            ll_guangbo.setVisibility(View.VISIBLE);
            showPlayAnim();
            setTextMarquee(tv_guangbo, sBu.toString());
        } else {
            ll_guangbo.setVisibility(View.GONE);
        }
        tv_home_text_3.setText(num);
        if (isToast) {
            String redes = bean.getString("redes");
            UiUtil.showToast(context, redes);
        }
    }

    @Override
    public Object onLSMsg(int arg0, Object... arg1) {
        if (arg0 == 101) {
            //重新查询是否绑定
            EntityBean bean = (EntityBean) JSONSerializer.getInstance().DeSerialize(PrefUtils.
                    getString(context, "carinfo", null), EntityBean.class);
            checkBind(bean, false);
        }
        return null;
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {
            exit();
            return false;
        }
        return null;
    }

    private void exit() {
        if (!this.isExit) {
            this.isExit = true;
            Toast.makeText(context, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            this.mHandler.sendEmptyMessageDelayed(0, 2000L);
        } else {
            ((MainActivity) context).finish();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public void OnDestroy() {
        regEvent(false);
        ll_homepage_entercompensate = null;
        ll_homepage_personinfo = null;
        ll_homepage_myaccident = null;
        mHandler = null;
        gpsover = false;
        view = null;
        if (null != mLocationClient) {
            mLocationClient.unRegisterLocationListener(this);
            mLocationClient = null;
        }
        if (null != dialog) {
            dialog.dismiss();
            dialog = null;
        }
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        super.OnDestroy();
    }

    /**
     * 退出登录
     */
    private void logout() {
        UiUtil.showDialog(context, "是否退出当前账号", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清空sp的账号，密码，token，发全局消息
                PrefUtils.removeStringData(context, "loginInfo");
                PrefUtils.removeStringData(context, "loginUserName");
                PrefUtils.removeStringData(context, "loginPassword");
                //清除缓存
                mApplication.setLoginInfo(null);
                mApplication.setToken(null);
                UiUtil.showToast(context, "退出登录成功");
                //回到登录页
                if (FrameworkManager.getInstance().isPopForm()) {
                    FrameworkManager.getInstance().closePopForm();
                }
                FrameworkManager.getInstance().destroyAllForm();
            }
        });
    }

    /**
     * 获取areid，经纬度
     */
    private void createAreaId(final String lat, final String lon) {
        EntityBean bean = new EntityBean();
        // 经纬度
        bean.set("maplon", lon);
        bean.set("maplat", lat);
        bean.set("userflag", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        LoadDataManagerCar.getInstance(context).callService(null,
                ((BaseApplication) context.getApplicationContext()).getServerUrl(), URLConstant.JJAPPGETWEATHER,
                bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                        if (null != result) {
                            String restate = ((EntityBean) result).getString("restate");
                            String redes = ((EntityBean) result).getString("redes");
                            if ("1".equals(restate)) {
                                String areaid = ((EntityBean) result).getString("data");
                                String mapaddress = ((EntityBean) result).getString("mapaddress");
                                mApplication.setAreaid(areaid);
                                mApplication.setAddress(mapaddress);
                                mApplication.setLatitude(lat);
                                mApplication.setLongitude(lon);
                                gpsover = true;
                            } else {
                                showsingle(context, redes);
                            }
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                        Toast.makeText(context, "数据加载失败，请检查网络是否连接", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                    }
                });
    }

    /**
     * 定位回调方法
     */
    @Override
    public void onReceiveLocation(BDLocation location) {
        if (null != location) {
            // 停止定位
            if (null != mLocationClient && mLocationClient.isStarted()) {
                mLocationClient.stop();
            }
            String cityCode = location.getCityCode();
            if (StringUtils.isEmpty(cityCode)) {
                AlertDialog alertDialog = UiUtil.showMainDialog(context, "快处快赔警用版",
                        "请打开权限管理，授权定位所在城市", "取消", "确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                context.startActivity(intent);
                            }
                        }
                );
                alertDialog.show();
                return;
            }
            createAreaId(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
        } else {
            if (null != dialog) {
                dialog.cancel();
            }
        }
    }

    private void showsingle(final Context context, String redes) {
        UiUtils.showSingleDialog(context, R.mipmap.a_32, redes, "确认", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }

    /**
     * 显示播放的动画效果
     */
    private void showPlayAnim() {
        iv_guangbo.setImageResource(R.drawable.record_voice_playanim_new);
        AnimationDrawable anim = (AnimationDrawable) iv_guangbo.getDrawable();
        anim.start();
    }

    private void setTextMarquee(TextView textView, String text) {
        if (textView != null) {
            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            textView.setSingleLine(true);
            textView.setSelected(true);
            textView.setFocusable(true);
            textView.setFocusableInTouchMode(true);
            textView.setText(text);
        }
    }

    /**
     * 时间限制
     */
    private void queryTime() {
        EntityBean bean = new EntityBean();
        bean.set("userflag", mApplication.getKckpName());//用户名
        bean.set("token", mApplication.getToken());
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        LoadDataManagerCar.getInstance(context).callService(null, mApplication.getServerUrl(),
                URLConstant.JJAPPCHECKTIMEISTRUE, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (null != result) {
                            String restate = ((EntityBean) result).getString("restate");
                            String redes = ((EntityBean) result).getString("redes");
                            if ("1".equals(restate)) {
                                //判断是否打开gps，没有打开跳转到提示打开gps界面，已经打开进入安全提示,获取areaid并存入application中
                                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                                    //跳转到提示打开gps界面
                                    OpenGpsView opengpsview = new OpenGpsView(context);
                                    FrameworkManager.getInstance().showNewForm(context, opengpsview);
                                } else {
                                    if (gpsover) {
                                        //跳转到推荐二维码页面
                                        QRCodeView chooseaccidenttypeview = new QRCodeView(context);
                                        FrameworkManager.getInstance().showNewForm(context, chooseaccidenttypeview);
                                    } else {
                                        mLocationClient.start();
                                        dialog.show();
                                    }
                                }
                            } else {
                                showsingle(context, redes);
                            }
                        }

                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(getContext(), "网络服务故障，请稍后重试");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }
}
